import { createHttpLink, ApolloLink, from } from '@apollo/client/core'
import { loadErrorMessages, loadDevMessages } from '@apollo/client/dev'
import { cache } from '@/utils'

/**
 * 开发环境 提示错误
 */
if (import.meta.env.MODE === 'development') {
  loadDevMessages()
  loadErrorMessages()
}

// 与 API 的 HTTP 连接
const httpLink = createHttpLink({
  uri: import.meta.env.VITE_GQL_BASE_URL
})

/**
 * 设置请求拦截
 */
const requestLink = new ApolloLink((operation, forward) => {
  const token = cache.getToken()
  operation.setContext({
    headers: {
      token: token ? token : null,
      start: new Date().getTime()
    }
  })

  return forward(operation)
})

/**
 * 设置响应拦截
 */
const responseLink = new ApolloLink((operation, forward) => {
  return forward(operation).map(res => {
    if (res.errors) {
      // return res
    }
    return res
  })
})

export const link = from([requestLink, responseLink, httpLink])
